<template>
  <div class="range-area">
    <CustomerForm ref="CustomerForm">
      <template #title>
        <Title v-if="!afterShow" title="客户信息录入"></Title>
      </template>
    </CustomerForm>
    <CustomerDistribute v-if="!afterShow" ref="CustomerDistribute">
      <template #title>
        <Title title="分配动作"></Title>
      </template>
    </CustomerDistribute>
  </div>
</template>

<script lang="ts">
/**
 * 导入单个客户组件
 */
import { Component, Vue, Ref, Prop } from 'vue-property-decorator'
import { commonAction, deepClone, checkHideTel } from '@/utils/common'
import CustomerForm from '../components/customerForm.vue'
import CustomerDistribute from '../components/customerDistribute.vue'
import Title from '../common/title.vue'
import { CommonModule } from '@/store/modules/common'
@Component({
  name: 'AddCustomer',
  components: {
    CustomerForm,
    CustomerDistribute,
    Title
  }
})
export default class AddCustomer extends Vue {
  [x: string]: any
  @Ref() private readonly CustomerForm
  @Ref() private readonly CustomerDistribute
  @Prop() private afterShow

  get getCustomerAllLabels () {
    let labelList = this.$store.state.common.publicCache.customerAllLabels || []
    labelList = labelList.filter(v => v.enabled)
    return labelList.map(v => ({ value: v.name, key: v._id }))
  }

  get getUserList () {
    return this.$store.state.common.publicCache.userList.map(v => ({ value: `${v.agentName} 【${v.agentNumber}】`, key: v._id }))
  }

  get getRegionList () {
    return this.$store.state.common.publicCache.region.result || []
  }

  get getCusInputCon () { // 获取录入面板配置
    const inputConfs = (CommonModule as any).publicCache.customerInputConfig || []
    inputConfs.forEach(item => {
      if (item.field === 'labels') { // 客户标签
        item.choices = this.getCustomerAllLabels || []
      } else if (['lastCallUser', 'lastChatUser', 'updateUser', 'createUser', 'firstOwner', 'owner'].includes(item.field)) { // 跟人有关的字段
        item.choices = this.getUserList || []
      } else if (item.field === 'region') { // 省市区
        item.options = {}
        item.options.children = this.getRegionList || []
      }
    })
    return inputConfs
  }

  private validateOther = (rule, arr, callback) => { // 手机号，QQ,邮箱等多个表单的必填校验
    let flag = false
    const newArr = arr || []
    newArr.forEach(item => {
      if (item.value) {
        flag = true
      }
    })
    if (!flag) {
      callback(new Error('必填'))
    } else {
      callback()
    }
  }

  public updatePhone (newData: any) { // 通话默认把号码带进去表单
    console.log(newData, '========')
    this.$nextTick(() => {
      this.CustomerForm.updatePhone([{ value: newData.phone || '', memo: '' }]) // 清空数据
    })
  }

  public initData () { // 初始化数据
    const rules = {}
    this.getCusInputCon.map(item => {
      if (item.required) {
        if (item.type === 'other') {
          rules[item.field] = [{
            required: true,
            validator: this.validateOther,
            trigger: 'blur'
          }]
        } else {
          rules[item.field] = [{
            required: true,
            trigger: 'blur',
            message: '必填'
          }]
        }
      }
    })
    this.$nextTick(() => {
      this.CustomerForm.clearData() // 清空数据
      if (!this.afterShow) {
        this.CustomerDistribute.clearData() // 清空数据
      }
      this.CustomerForm.setData(this.getCusInputCon, rules)
    })
  }

  public checkForm () { // 售后云
    const { status, newForm } = this.CustomerForm.checkForm()
    return {
      status,
      newForm
    }
  }

  private isSame (arr: any) {
    let same = false
    same = arr.some((item, index) => item.value === (arr[index + 1] && arr[index + 1].value))
    return same
  }

  private getTextName (key: any) {
    switch (key) {
      case 'mobile':
        return '手机号'
      case 'email':
        return '邮箱'
      case 'qq':
        return 'qq'
      case 'wechat':
        return '微信'
    }
  }

  private handleHideTel (arr) { // 手机号隐藏，在保存时候要匹配下，
    arr.forEach(item => {
      if (item.value === checkHideTel(item.bakValue)) { // 如果当前的value跟bakValue处理之后的一样，说没做改动，请求后端存储，用bakValue
        item.value = item.bakValue
      }
      delete item.bakValue
    })
    return arr || []
  }

  public saveForm (wechat?: any, labels?: any) { // 保存
    const { status, newForm } = this.CustomerForm.checkForm()
    const cloneForm = deepClone(newForm)
    let distributeStatus = true
    let disForm = {}
    if (this.CustomerDistribute.distribute) {
      distributeStatus = this.CustomerDistribute.checkForm().distributeStatus
      disForm = this.CustomerDistribute.checkForm().disForm
    }
    if (status && distributeStatus) {
      const sameVal: any = []
      const text: any = []
      Object.keys(cloneForm).map(item => {
        if (['mobile', 'email', 'qq', 'wechat'].includes(item) && cloneForm[item] && cloneForm[item].length > 1) {
          cloneForm[item] = cloneForm[item].filter(v => v.value) // 去掉空值
          sameVal.push(this.isSame(cloneForm[item]))
          text.push(this.getTextName(item))
        } else if (['mobile', 'email', 'qq', 'wechat'].includes(item) && JSON.stringify(cloneForm[item]) === '[{}]') { // 处理 文本框多个手机号、邮箱、微信号、qq 为空的情况
          cloneForm[item] = []
        }
        if (item === 'mobile') {
          cloneForm.mobile = this.handleHideTel(cloneForm.mobile || [])
        }
      })
      const tMessage = sameVal.findIndex(v => v)
      if (tMessage > -1) {
        return this.$message.error(`${text[tMessage]}重复`)
      }
      const sendData = {
        ...cloneForm,
        ...disForm,
        createMethod: wechat ? 'WEBCHAT' : 'INSERT'
      }
      const actionData = { url: '/server-crm/action/customer/add', method: 'POST', data: sendData }
      commonAction(actionData).then(res => {
        if (res.success) {
          this.$message.success('录入成功')
          this.CustomerForm.clearData() // 清空数据
          this.CustomerDistribute.clearData() // 清空数据
          if (!this.afterShow) {
            this.$emit('addUpdateTableList')
          }
          this.$emit('updateRelationCusInfo', res)
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
>>> .el-form
  margin 16px 0 24px !important
.range-area
  .title
    height 33px
    font-size 14px
    font-weight 600
    overflow hidden
    margin 16px 0px
    .titlespan
      border-left 5px solid $c-main
      line-height 20px
      padding 0 10px
      display inline-block
      margin 6px 0px
  .urlList
    border 1px solid #E7E9ED
    border-radius 4px
    overflow hidden
    padding 5px
    .urlListItem
      border 1px solid #E7E9ED
      border-radius 4px
      overflow hidden
      padding 5px 10px
      margin 5px
      width 170px
      box-sizing border-box
      display inline-block
      text-overflow ellipsis
      white-space nowrap
    .border
      border 1px solid $c-main
</style>
